from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.conn import *
from libs.send_email import send_email_with_config
from libs.utils import *
from libs.check_service import start_iperf3_service, stop_iperf3_service

configs_bp = Blueprint('configs', __name__)

@configs_bp.route('/api/get_configs', methods=['GET'])
@jwt_required()
def get_configs():
    rows = fetchall("SELECT config_name, config_value FROM configs")
    return { 'status': 'ok', 'data': rows }

# save_receiver_email_configs
@configs_bp.route('/api/save_receiver_email_configs', methods=['POST'])
@jwt_required()
def save_receiver_email_configs():
    email_receiver_address = request.json.get('email_receiver_address')
    email_subject = request.json.get('email_subject')
    if is_valid_emails(email_receiver_address) == False:
        return { 'status': 'error', 'data': '邮箱地址格式不正确' }
    set_config('email_subject', email_subject)
    set_config('email_receiver_address', email_receiver_address)
    set_config('email_common_target', email_receiver_address)
    return { 'status': 'ok', 'data': 'success' }


# save_email_configs
@configs_bp.route('/api/save_email_configs', methods=['POST'])
@jwt_required()
def save_email_configs():
    email_smtp_server = request.json.get('email_smtp_server')
    email_smtp_port = int(request.json.get('email_smtp_port'))
    email_sender_address = request.json.get('email_sender_address')
    email_sender_password = request.json.get('email_sender_password')
    if is_valid_email(email_sender_address) == False:
        return { 'status': 'error', 'data': '邮箱地址格式不正确' }
    set_config('email_smtp_server', email_smtp_server)
    set_config('email_smtp_port', email_smtp_port)
    set_config('email_sender_address', email_sender_address)
    set_config('email_sender_password', email_sender_password)
    return { 'status': 'ok', 'data': 'success' }

# save_log_configs
@configs_bp.route('/api/save_log_configs', methods=['POST'])
@jwt_required()
def save_log_configs():
    log_maxcount = int(request.json.get('log_maxcount'))
    if log_maxcount < 1000 or log_maxcount > 50000:
        return { 'status': 'error', 'data': '最大日志数必须在1000和50000之间' }
    set_config('log_maxcount', log_maxcount)
    return { 'status': 'ok', 'data': 'success' }

# save_notice_configs
@configs_bp.route('/api/save_notice_configs', methods=['POST'])
@jwt_required()
def save_notice_configs():
    alarm_notice_interval = int(request.json.get('alarm_notice_interval'))
    notice_force_relay = int(request.json.get('notice_force_relay'))
    if alarm_notice_interval < 10:
        return { 'status': 'error', 'data': '最小通知间隔不得小于10秒' }
    # if notice_force_relay not in [0, 1]:
    #     return { 'status': 'error', 'data': 'notice_force_relay must be 0 or 1' }
    set_config('alarm_notice_interval', alarm_notice_interval)
    # set_config('notice_force_relay', notice_force_relay)
    return { 'status': 'ok', 'data': 'success' }

# save_app_self_configs
@configs_bp.route('/api/save_app_self_configs', methods=['POST'])
@jwt_required()
def save_app_self_configs():
    app_id = request.json.get('app_id')
    app_name = request.json.get('app_name')
    set_config('app_id', app_id)
    set_config('app_name', app_name)
    return { 'status': 'ok', 'data': 'success' }

# create_app_secret
@configs_bp.route('/api/create_app_secret', methods=['POST'])
@jwt_required()
def create_app_secret():
    app_secret = generate_random_string()
    set_config('app_secret', app_secret)
    return { 'status': 'ok', 'data': app_secret }

# save_relay_configs
@configs_bp.route('/api/save_relay_configs', methods=['POST'])
@jwt_required()
def save_relay_configs():
    relay_url = request.json.get('relay_url')
    relay_password = request.json.get('relay_password')
    set_config('relay_url', relay_url)
    set_config('relay_password', relay_password)
    return { 'status': 'ok', 'data': 'success' }

# app_register_to_service
@configs_bp.route('/api/app_register_to_service', methods=['POST'])
@jwt_required()
def app_register_to_service():
    relay_url = get_config('relay_url').strip().strip('/')
    relay_password = get_config('relay_password')
    try:
        res = requests.post(relay_url + '/app_register', json = {
            'app_id': get_config('app_id'),
            'app_name': get_config('app_name'),
            'app_secret': get_config('app_secret'),
            'password': relay_password
        })
        print(res.text)
        if res.status_code == 200:
            if res.json()['status'] == 'ok':
                return { 'status': 'ok', 'data': 'success' }
            else:
                return { 'status': 'error', 'data': res.json()['data'] }
        else:
            return { 'status': 'error', 'data': '无法连接到中继服务' }
    except Exception as e:
        return { 'status': 'error', 'data': str(e) }

# relay_service_enable
@configs_bp.route('/api/relay_service_enable', methods=['POST'])
@jwt_required()
def relay_service_enable():
    relay_service_enable = int(request.json.get('relay_service_enable'))
    if relay_service_enable not in [0, 1]:
        return { 'status': 'error', 'data': 'relay_service_enable must be 0 or 1' }
    set_config('relay_service_enable', relay_service_enable)
    return { 'status': 'ok', 'data': 'success' }

# relay_register_enable
@configs_bp.route('/api/relay_register_enable', methods=['POST'])
@jwt_required()
def relay_register_enable():
    relay_register_enable = int(request.json.get('relay_register_enable'))
    if relay_register_enable not in [0, 1]:
        return { 'status': 'error', 'data': 'relay_register_enable must be 0 or 1' }
    set_config('relay_register_enable', relay_register_enable)
    return { 'status': 'ok', 'data': 'success' }

# save_relay_service_configs
@configs_bp.route('/api/save_relay_service_configs', methods=['POST'])
@jwt_required()
def save_relay_service_configs():
    relay_service_password = request.json.get('relay_service_password')
    set_config('relay_service_password', relay_service_password)
    return { 'status': 'ok', 'data': 'success' }

# notice_force_relay
@configs_bp.route('/api/config_notice_force_relay', methods=['POST'])
@jwt_required()
def notice_force_relay():
    notice_force_relay = int(request.json.get('notice_force_relay'))
    if notice_force_relay in [0, 1]:
        set_config('notice_force_relay', notice_force_relay)
        return { 'status': 'ok', 'data': 'success' }
    else:
        return { 'status': 'error', 'data': 'notice_force_relay must be 0 or 1' }

@configs_bp.route('/api/config_email_enable', methods=['POST'])
@jwt_required()
def config_email_enable():
    email_enable = int(request.json.get('email_enable'))
    if email_enable in [0, 1]:
        set_config('email_enable', email_enable)
        return { 'status': 'ok', 'data': 'success' }
    else:
        return { 'status': 'error', 'data': 'email_enable must be 0 or 1' }

# 保存服务器配置
@configs_bp.route('/api/save_cmd_server_configs', methods=['POST'])
@jwt_required()
def save_cmd_server_configs():
    cmd_server_ip = request.json.get('cmd_server_ip')
    cmd_server_port = int(request.json.get('cmd_server_port'))
    # 检测IP和端口格式是否合法
    if is_valid_ip_or_domain(cmd_server_ip) == False:
        return {'status': 'error', 'data': 'IP地址格式不正确' }
    if cmd_server_port < 1 or cmd_server_port > 65535:
        return {'status': 'error', 'data': '端口号必须在1到65535之间' }
    set_config('cmd_server_ip', cmd_server_ip)
    set_config('cmd_server_port', cmd_server_port)
    return { 'status': 'ok', 'data': 'success' }

# 保存iperf3配置
@configs_bp.route('/api/save_iperf3_configs', methods=['POST'])
@jwt_required()
def save_iperf3_configs():
    cmd_iperf3_server_port = int(request.json.get('cmd_iperf3_server_port'))
    # 检测端口格式是否合法
    if cmd_iperf3_server_port < 1 or cmd_iperf3_server_port > 65535:
        return {'status': 'error', 'data': '端口号必须在1到65535之间' }
    set_config('cmd_iperf3_server_port', cmd_iperf3_server_port)
    return { 'status': 'ok', 'data': 'success' }

# 是否开启ipref3配置
@configs_bp.route('/api/config_iperf3_enable', methods=['POST'])
@jwt_required()
def config_iperf3_enable():
    cmd_iperf3_server_enable = int(request.json.get('cmd_iperf3_server_enable'))
    if cmd_iperf3_server_enable in [0, 1]:
        set_config('iperf3_enable', cmd_iperf3_server_enable)
        if cmd_iperf3_server_enable == 1:
            start_iperf3_service()
        else:
            stop_iperf3_service()
        return { 'status': 'ok', 'data': 'success' }
    else:
        return { 'status': 'error', 'data': 'cmd_iperf3_server_enable must be 0 or 1' }



# test email
@configs_bp.route('/api/test_email', methods=['POST'])
@jwt_required()
def test_email():
    email_smtp_server = request.json.get('email_smtp_server')
    email_smtp_port = int(request.json.get('email_smtp_port'))
    email_sender_address = request.json.get('email_sender_address')
    email_sender_password = request.json.get('email_sender_password')
    email_subject = request.json.get('email_subject')
    email_receiver_address = request.json.get('email_receiver_address')
    if is_valid_email(email_sender_address) == False:
        return { 'status': 'error', 'data': '发送者邮箱地址无效' }
    if is_valid_emails(email_receiver_address) == False:
        return { 'status': 'error', 'data': '接收者邮箱地址无效' }
    result, message = send_email_with_config(email_receiver_address, email_subject, "测试内容", {
        'email_smtp_server': email_smtp_server,
        'email_smtp_port': email_smtp_port,
        'email_sender_address': email_sender_address,
        'email_sender_password': email_sender_password
    })
    if result:
        return { 'status': 'ok', 'data': '邮件发送成功' }
    else:
        return { 'status': 'error', 'data': '邮件发送失败, 错误信息: ' + message }
